package taskscheduleservicelogic

import (
	"context"
	"github.com/google/uuid"
	"go-zero-admin/pkg/utils"

	"github.com/jinzhu/copier"
	"github.com/pkg/errors"
	"go-zero-admin/application/job/rpc/internal/model"
	"gorm.io/gorm"

	"go-zero-admin/application/job/rpc/internal/svc"
	job "go-zero-admin/application/job/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateCronLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateCronLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateCronLogic {
	return &CreateCronLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// CreateCron 创建定时任务接口
func (l *CreateCronLogic) CreateCron(in *job.CreateCronReq) (*job.CreateCronRes, error) {
	if !errors.Is(l.svcCtx.DB.Where("exec_cmd = ?", in.CreateCronInfo.ExecCmd).First(&model.TaskSchedule{}).Error, gorm.ErrRecordNotFound) {
		return nil, errors.New("存在相同命令")
	}
	var task model.TaskSchedule
	if err := copier.Copy(&task, in.CreateCronInfo); err != nil {
		return nil, err
	}
	task.UniqueID = uuid.NewString()
	if err := l.svcCtx.DB.Create(&task).Error; err != nil {
		return nil, err
	}
	var createdTask model.TaskSchedule
	if err := l.svcCtx.DB.First(&createdTask, task.ID).Error; err != nil {
		return nil, err
	}
	res := &job.CreateCronRes{
		TaskScheduleInfo: &job.TaskScheduleInfo{},
	}
	if err := copier.Copy(res.TaskScheduleInfo, &createdTask); err != nil {
		return nil, err
	}
	res.TaskScheduleInfo.CreatedAt = utils.SafeUnix(&task.CreatedAt)
	res.TaskScheduleInfo.UpdatedAt = utils.SafeUnix(&task.UpdatedAt)
	res.TaskScheduleInfo.LastExecuteTime = utils.SafeUnix(task.LastExecuteTime)
	return res, nil
}
